<template>
	<view class="content" :style="{height: tabHeightVal}">
		<popup-layer ref="popupRef" :direction="'left'">
			
			<view style="height: 93%;font-size: 30rpx;">
				<view class="box" style="text-align: center;">
					<view>筛选</view>
				</view>
				<view class="box">
					<view class="popupspan">盘点单名称:</view>
					<view class="popupinput"><input type="text" v-model="inputdjmc" placeholder="请输入盘点单名称"
							placeholder-class="inputff" /></view>
							
				</view>
				<view class="box">
					<view class="popupspan">盘点单编码:</view>
					<view class="popupinput">

						<input type="text" v-model="inputdjbm" placeholder="请输入盘点单编码" placeholder-class="inputff" />

					</view>
				</view>
				
				
			</view>
			<view class="box"
				style="border-bottom: 0px #bfbfbf solid;border-top: 1rpx #bfbfbf solid;padding-top: 5rpx;padding-bottom: 5rpx;">
				<view class="popupspan"
					style="width: 49.5%;text-align: center;border-right: 1px #bfbfbf solid;padding-left: 0rpx;font-size: 28rpx;"
					@tap="chaxunreset()">重置</view>
				<view class="popupinput" style="width: 49.5%;text-align: center;color: #6D8AF9;padding-right: 0rpx;"
					@tap="chaxunok()">确定</view>
			</view>


		</popup-layer>
		<view class="newbuttonleft" :style="{display:disPValue}" @tap="sxchaxun()">
			<view style="float: left;font-size: 28rpx;color: #515159;margin-left: 15rpx;">盘点单总数:{{pdzs}}</view>
			
		</view>
		<view class="newbutton" :style="{display:disPValue}" @tap="sxchaxun()">
			<image :src="srcsys" class="item-icon-sys" style="float: left;" mode=""></image>
			<view style="float: left;font-size: 28rpx;color: #bfbfbf;"></view>
		</view>

		<!-- 当设置tab-width,指定每个tab宽度时,则不使用flex布局,改用水平滑动 -->
		<home-me-tabs v-model="tabIndex" :tabs="tabs" :fixed="true" ref="metabs" v-on:pChangeType="change"
			v-on:pback="newback">
		</home-me-tabs>

		<swiper :style="{height: height}" :current="tabIndex" @change="swiperChange">
			<swiper-item v-for="(tab,i) in tabs" :key="i">
				<view v-if="i==0">
					<HomeHand :i="i" :index="tabIndex" :tabs="tabs" ref="MescrollItem" 
					v-on:gotorefer="gotorefer"></HomeHand>
				</view>
				<view v-else>
					<HomeFinsh :i="i" :index="tabIndex" :tabs="tabs" ref="MescrollItem"></HomeFinsh>
				</view>
				
			</swiper-item>
		</swiper>

		<tki-tree ref="tkitree" :selectParent="selectParent" :multiple="multiple" :range="treelist" :foldAll="flod"
			rangeKey="Name" :title="title" @confirm="treeConfirm" @cancel="treeCancel"></tki-tree>
	<tab-bar class="fixs" ref='commentTabbat' :actives='active'></tab-bar>
	</view>
</template>

<script>
	import MescrollBody from "@/components/mescroll-uni/mescroll-body.vue"
	import MescrollUni from "@/components/mescroll-uni/mescroll-uni.vue"
	import HomeHand from "./home_hand.vue";
	import HomeFinsh from "./home_finsh.vue";
	import homemetabs from "@/components/home-me-tabs/home-me-tabs.vue";
	import popupLayer from "@/components/popup-layer/popup-layer.vue";
	import tkiTree from '@/components/tki-tree-asset/tki-tree.vue';
	import tabBar from '@/components/tabbar/tabbar2.vue'

	import IndexDBCache from "@/pages/API/sqllite/indexDB.js"; // 你的文件的位置
	var self;
	export default {
		components: {
			MescrollBody,
			MescrollUni,
			HomeHand,
			HomeFinsh,
			homemetabs,
			popupLayer,
			tkiTree,
			tabBar
		},
		data() {
			return {
				height: "95%", // 需要固定swiper的高度
				tabs: [{
					name: '进行中',
					code: '',
					id: '',
					count:0
				}, {
					name: '已结束',
					code: '',
					id: '',
					count:0
				}],
				tabIndex: 0, // 当前tab的下标
				list: [],
				multiple: false,
				selectParent: true,
				flod: false,
				title: "选择资产位置",
				titleColor: "#6D8AF9",
				showTreeValue: false,
				DocumentId: "",
				disPValue: "block",
				srcsys: "../../static/images/icon-sxuan2.png",
				srcpximg: "../../static/images/icon-ss-down.png",
				srcmore: "../../static/images/AndroidMore.png",
				//srcsys: "../../static/images/icon-sxuan.png",
				inputdjbm: "",
				inputdjmc: "",
				inputzclb: "请选择资产类别 >",
				inputzcwz: "请选择资产位置 >",
				inputzclbid: "",
				inputzcwzid: "",
				treelist: [],
				multiple: false,
				selectParent: true,
				flod: false,
				title: "选择资产类别",
				selectvalue: "",
				showTreeValue: false,
				ShowQueryValue: false,
				active: 3,
				pdzs:0,
				loginName:"",
				db:null,
			}
		},
		computed: {
			tabHeightVal() {
				return uni.getSystemInfoSync().windowHeight + 'px'
			}
		},
		onBackPress(options) {

			if (this.showTreeValue == true) {
				this.showTreeValue = false;
				this.$refs.tkitree._hide();
				return true;
			} else {
				if (this.ShowQueryValue == true) {
					this.ShowQueryValue = false;
					this.$refs.popupRef.close();
					return true;
				} else {
					uni.setStorageSync('setStatusIndexFunc', 0)
					uni.navigateTo({
						url: '../home/Index'
					});
					return true;
				}

			}
		},
		onNavigationBarButtonTap(val) {
			//return;
			if (val.index == 1) { //搜索
				this.selectvalue="zcwz";
				this.showTree();
				this.title = "请选择资产位置";
				this.loadStoreplase();
			}
			//if (val.index == 0) {
				// 只允许通过相机扫码
				//this.qiwxsys();
			//	uni.navigateTo({
				//	url: '../home/scan-stock?newType=stock',
			//	});
			//}
			
			if (val.index == 0) {
				
				uni.setStorageSync("currzcwzid",this.inputzcwzid);
				uni.navigateTo({
						url: '../home/datalocal',
					});				
				}
				
		},
provide() {
			return {
				_mainFuncInit: this._mainFuncInit
			}
		},
		onShow() {

		},
		methods: {
			/**
			 * @name 公共点击函数
			 * */
			 gotorefer(){
				 console.log(111);
				this.newload();
				this.change();
			 },
			_mainFuncInit() {
				this.active = uni.getStorageSync('setStatusIndexFunc') || 0
				console.log(this.active)
				if (this.active == 1) {
					uni.navigateTo({
						url: '../asset/myasset',
					});
				} else if (this.active == 4) {
					uni.navigateTo({
						url: '../home/mysetup',
					});
				} else if (this.active == 0) {
					uni.navigateTo({
						url: '../home/Index',
					});
				}
			},
			/**
			 * @name 首页数据初始化 
			 * */
			_initData() {
				this._mainFuncInit();
			},
			newback() {
				console.log("子页面调用2");

				uni.navigateBack();
			},
			// 轮播菜单
			swiperChange(e) {
				this.tabIndex = e.detail.current;
				console.log("子页面调用");
				this.$refs.MescrollItem[this.tabIndex]._aaaaCCCC();
			},
			change() {
				console.log("子页面调用");
				//console.log(this.$refs.MescrollItem[0]);
				this.$refs.MescrollItem[this.tabIndex]._aaaaCCCC();

			},
			qiwxsys() {

				self = this;
				var url = window.location.href.split("#")[
				0]; //该paramUrl 为你使用微信sdk-js相关接口的页面地址 该地址需要配置到应用后台的可信域名下，你也可以理解为项目访问的地址;
				console.log(url);
				uni.request({
					url:uni.getStorageSync("localurl")+'/Documents/WX_GetToken', //仅为示例，并非真实接口地址。
					data: {
						url: url
					},
					method: "POST",
					success: res2 => {
						if (res2.data.successed == true) {
							console.log(res2);
							//alert("调用成功");
							jWeixin.config({
								beta: true, // 必须这么写，否则wx.invoke调用形式的jsapi会有问题
								debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
								appId: res2.data.model.appId, // 必填，企业微信的corpID
								timestamp: res2.data.model.timpstamp, // 必填，生成签名的时间戳
								nonceStr: res2.data.model.noncestr, // 必填，生成签名的随机串
								signature: res2.data.model.signature, // 必填，签名，见 附录-JS-SDK使用权限签名算法
								jsApiList: ["scanQRCode",
									"openLocation"] // 必填，需要使用的JS接口列表，凡是要调用的接口都需要传进来
							});
							jWeixin.ready(function() {
								jWeixin.checkJsApi({
									jsApiList: ["invoke",
									"scanQRCode"], // 需要检测的JS接口列表，所有JS接口列表见附录2,
									success: res => {
										console.log(res);
									}
								});
								jWeixin.invoke("enterpriseVerify", {}, res => {});
								jWeixin.scanQRCode({
									desc: 'scanQRCode desc',
									needResult: 1, // 默认为0，扫描结果由企业微信处理，1则直接返回扫描结果，
									scanType: ["qrCode"], // 可以指定扫二维码还是一维码，默认二者都有
									success: function(res) {
										const resmodel = JSON.parse(res.resultStr);
										if (resmodel.唯一标识 != undefined) {
											uni.request({
												url:uni.getStorageSync("localurl")+'/ServerAPI/Document_Get_Detail_List',
												data: {
													DocumentId: self.DocumentId,
													pageSize: 20,
													_r: "813efd8e-1ac0-4cc8-8c35-3d502f680353",
													pageIndex: 0,
													"资产编码": resmodel.资产编码
												},
												success: (res) => {
													console.log(res);
													if (res.data.successed ==
														true) {
														var mydata = [];
														var newrows = JSON
															.parse(res.data
																.rows);
														for (var i = 0; i <
															newrows.length; i++
															) {
															var valueRows =
																newrows[i]
																.toString()
																.split(',');
															var datarow = {};
															for (var j = 0; j <
																res.data
																.columns
																.length; j++) {
																datarow[res
																		.data
																		.columns[
																			j]
																		.字段名] =
																	valueRows[
																		j];
															}
															mydata.push(
																datarow);
														}
														if (mydata.length >
															0) {
															uni.navigateTo({
																url: '../stock/StockDocumentAsset?AssetCode=' +
																	resmodel
																	.资产编码 +
																	'&type=0',
															});
														} else {
															uni.showToast({
																icon: 'none',
																title: '扫描资产不在盘点单内'
															});
														}
													}
												},
												fail: (err) => {
													console.log(err);
													//  请求失败,隐藏加载状态
													this.mescroll.endErr()
												}
											})

										} else {
											uni.showToast({
												icon: 'none',
												title: '无法识别二维码'
											});
										}
									},
									error: function(res) {
										if (res.errMsg.indexOf('function_not_exist') > 0) {
											alert('版本过低请升级')
										}
									}
								});
							});
							//this.model = res.data.model;
						} else {
							console.log(res2);
							uni.showToast({
								icon: 'none',
								title: res2.data.responseState,
								duration: 1500,
							});
						}
						uni.hideNavigationBarLoading();
					},
					fail: () => {

						uni.showToast({
							icon: 'none',
							title: '网络异常,请稍后重试'
						});
					}
				});
			},
			sxchaxun() {
				this.ShowQueryValue = true;
				this.$refs.popupRef.show();
			},
			chaxunclose() {
				this.ShowQueryValue = false;
				this.$refs.popupRef.close();
			},
			getCount(){
				return tabs[0].count+tabs[1].count;
			},
			chaxunreset() {
				this.inputdjbm="";
				this.inputdjmc="";
				uni.removeStorageSync("DetailSearchDJBM");
				uni.removeStorageSync("DetailSearchDJMC");
				

				//this.ShowQueryValue = false;
				//this.$refs.popupRef.close();
				//this.newload();
				//this.change();
			},
			chaxunok() {
				this.ShowQueryValue = false;
				this.$refs.popupRef.close();
				uni.setStorageSync("DetailSearchDJBM", this.inputdjbm);
				uni.setStorageSync("DetailSearchDJMC", this.inputdjmc);
			
				this.newload();
				this.change();
			},
			focusshow(e) {
				this.selectvalue = e.currentTarget.dataset.id;
				this.treelist = [];
				this.$refs.tkitree.oldtreeList = "";
				this.$refs.tkitree.servalue = "";

				if (e.currentTarget.dataset.id == "zclb") {
					this.showTree();
					this.title = "请选择资产类别";
					this.loadAssetType();
				} else if (e.currentTarget.dataset.id == "zcwz") {
					this.showTree();
					this.title = "请选择资产位置";
					this.loadStoreplase();
				}

			},
			getNetworkType() {
				//获取网络信息  
				
						this.isOpenDB();
					
			},
			isOpenDB() {
				//this.openDB();
				//indexDB.openDB('databaseName');
			},
			
			isNet() {
				//网络问题；  
				if (this.netWork == 'wifi' || this.netWork == '4g') {
					//console.log('初始化有网络');
					
					//this.createBuildTable();
					//this.getPointList() //默认加载未处理；   有网络下，正常调用接口 
			
				} else {
					//this.selPointList()    //无网络下调用数据库表中的数据；  
					//无网络时；  
					console.log('初始化无网络');
			
				}
			},
			// 确定回调事件
			treeConfirm(e) {
				this.showTreeValue = false;
				if (this.selectvalue == "zclb") {
					this.inputzclb = e[0].Name;
					this.inputzclbid = e[0].Id;
				} else if (this.selectvalue == "zcwz") {
					this.inputzcwz = e[0].Name;
					this.inputzcwzid = e[0].Id;
				}

			},
			// 取消回调事件
			treeCancel(e) {
				this.showTreeValue = false;
				console.log(e)
			},
			// 显示树形选择器
			showTree() {
				this.showTreeValue = true;
				this.$refs.tkitree._show();
			},
			loadAssetType() {
				self = this;

				uni.showNavigationBarLoading();
				uni.request({
					url:uni.getStorageSync("localurl")+'/Common/TreeSelector', //仅为示例，并非真实接口地址。
					data: {
						_Type: "AmsAssetTypes",
					},
					success: res2 => {

						if (res2.data.successed == true) {
							//console.log(res2.data.data);
							var _typelist = [];
							for (var i = 0; i < res2.data.data.length; i++) {
								var model = res2.data.data[i];
								var child = [];
								var _type = {};
								_type.Id = model.Id;
								_type.Name = model.Name;
								for (var j = 0; j < model.children.length; j++) {
									var model1 = model.children[j];
									var child1 = [];
									var _type1 = {};
									_type1.Id = model1.Id;
									_type1.Name = model1.Name;
									for (var s = 0; s < model1.children.length; s++) {
										var model2 = model1.children[s];
										var child2 = [];
										var _type2 = {};
										_type2.Id = model2.Id;
										_type2.Name = model2.Name;

										_type2.children = child2;
										child1.push(_type2);
									}
									_type1.children = child1;
									child.push(_type1);
								}

								_type.children = child;
								_typelist.push(_type);
							}
							self.treelist = _typelist;
							setTimeout(function() {
								uni.hideNavigationBarLoading();
							}, 1000);
							//this.model = res.data.model;
						}
					},
					fail: () => {

						uni.showToast({
							icon: 'none',
							title: '网络异常,请稍后重试'
						});
					}
				});

			},
			loadStoreplase() {
				self = this;
			
				uni.showNavigationBarLoading();
				let managePositionIds = uni.getStorageSync("managePositionIds");
				console.error(managePositionIds);
				this.request_tool({
					url:'/app/v1/position/treeData',
					type:'POST',
					data:{}
				}).then(res => {
						console.error(res);
						if (res.data.code == 2000) {
							let treedata= res.data.data;
							let newtreedata=[];
							self.filterParentNode(managePositionIds,treedata,newtreedata);
							self.treelist=newtreedata;
							setTimeout(function () {
							  uni.hideNavigationBarLoading();
							}, 2000);
							this.$refs.tkitree.oldtreeList="";
							this.$refs.tkitree.servalue="";
							this.showTree();
							//this.model = res.data.model;
						}else{
							uni.showToast({
								icon: 'none',
								title: res.data.msg
								});
						}
						}).catch(err => {
				  console.error(err);
				  
				});
			
			},
			filterParentNode(ids,options,options2){
			      if(Array.isArray(ids)&&ids.length>0){
			        options.forEach(option=>{	
						if(ids.includes(option.id)){
							let newoption={
								"id": option.id,
								"code": option.code,
								"label": option.label,
								"isEnabled": option.isEnabled,
								"levelCode": option.levelCode,
								"parentLevelCode": option.parentLevelCode,
								"pathCode": option.pathCode,
								"entityName": option.entityName,
							}							
							let childrenarr=[];
							if(option.children){
							  this.filterParentNode(ids,option.children,childrenarr);
							}
							newoption.children=childrenarr;
							
							options2.push(newoption);
						}
			         
			        });
			      }else{							
							if(option.children){
								let childrenarr=[];
							  this.filterParentNode(ids,option.children,childrenarr);
							  if(childrenarr.length>0){
								  let newoption={
								  	"id": option.id,
								  	"code": option.code,
								  	"label": option.label,
								  	"isEnabled": "0",
								  	"levelCode": option.levelCode,
								  	"parentLevelCode": option.parentLevelCode,
								  	"pathCode": option.pathCode,
								  	"entityName": option.entityName,
								  }
									newoption.children=childrenarr;
									options2.push(newoption);
							  }
							}
						}
			    },
			newload() {
				self=this;
				
				//参数分别为数据库名称，数据库版本，返回的方法
				let userInfo = uni.getStorageSync("userInfo");
				let querydata={
						//"pageSize": 10,
						//"current": 0,
						manageUser:JSON.parse(userInfo).id,
						isAppCheckFinish:0
					};
				this.request_tool({
					url:'/app/v1/assetCheck/getCheckDocumentListAndTaskList',
					type:'POST', 
					data:querydata
				}).then(res => {
					console.log(res);
					if(res!=undefined){
						if (res.data.code == 2000) {
							if(res.data.data!=null){
								let mydata=res.data.data.convertCheckDocumentList;
								self.tabs[0].count=mydata.length;
								self.pdzs=mydata.length;
								//self.tabs[1].count=0;
								//self.pdzs=mydata.length;
								}else{
									self.tabs[0].count=0;
									self.pdzs=0;
								}
							}else{
								uni.showToast({
									icon: 'none',
									title: "请求失败"
								});
								self.jieshumethed();
							}
						}else{
							uni.showToast({
								icon: 'none',
								title: "接口请求超时"
							});
							self.jieshumethed("接口请求超时");
						}
					}).catch(err => {
					  console.error(err);
						uni.showToast({
							icon: 'none',
							title: err
						});				 
					  
					});
					
				querydata.isAppCheckFinish=1;
				this.request_tool({
					url:'/app/v1/assetCheck/getCheckDocumentListAndTaskList',
					type:'POST', 
					data:querydata
				}).then(res => {
					console.log(res);
					if(res!=undefined){
						if (res.data.code == 2000) {
							if(res.data.data!=null){
								let mydata=res.data.data.convertCheckDocumentList;
								//self.tabs[0].count=mydata.length;
								self.tabs[1].count=mydata.length;
								self.pdzs=self.pdzs+self.tabs[1].count;
								}else{
									self.tabs[1].count=0;
									self.pdzs=0;
								}
							}else{
								uni.showToast({
									icon: 'none',
									title: "请求失败"
								});
								self.jieshumethed();
							}
						}else{
							uni.showToast({
								icon: 'none',
								title: "接口请求超时"
							});
							self.jieshumethed("接口请求超时");
						}
					}).catch(err => {
					  console.error(err);
						uni.showToast({
							icon: 'none',
							title: err
						});				 
					  
					});
				
				

				
			},
			request_tool(options){
			 // 在这里可以对请求头进行一些设置
			 let baseUrl = uni.getStorageSync("localurl"); 

			console.log(options);
			  options.header = {
			      'Content-Type':'application/json',
			      Authorization: uni.getStorageSync("authorization")
			 }
			
			    return new Promise((resolve, reject) => {
			        uni.request({
			            url: baseUrl + options.url || '',
			            method: options.type || 'POST',
			            data: options.data || {},
			            header: options.header || {}      
			        }).then(data => {
			            let [err, res] = data;
						if(res.data.code==5001 || res.data.code==5002 ||
						res.data.code==5003 || res.data.code==5004){
							uni.removeStorageSync("LoginName");
							uni.removeStorageSync("userInfo");
							uni.removeStorageSync("authorization");
							uni.removeStorageSync("userToken")
							uni.removeStorageSync("userRoles");
							uni.removeStorageSync("userDept");
							uni.removeStorageSync("userReadDeptIds");
							uni.removeStorageSync("managePositionIds");
							uni.removeStorageSync("ASSETCODE");
							uni.navigateTo({
								url: '../login/login',
							});
						}
			            resolve(res);
			        }).catch(error => {
			            reject(error)
			        })
			    });
			}
			
		},

		onLoad(options) {
			self=this;
			uni.removeStorageSync("DetailSearchDJBM");
			uni.removeStorageSync("DetailSearchDJMC");
			uni.removeStorageSync("CurrStore");
			uni.removeStorageSync("CurrStoreName");
			const listdata =uni.getStorageSync("userinfo");
			self.loginName = listdata.LoginName;
			/*
			uni.getStorage({
				key: 'userinfo',
				success: function(newres) {
					const listdata = newres.data;
					self.loginName = listdata.LoginName;
				}
			});
			*/
			
			IndexDBCache.openDB('databaseName');
			
			this.newload();
		}
	}
</script>

<style>
	.item-icon-sys {
		width: 40upx;
		height: 40upx;
	}
.item-icon-px {
		width: 20upx;
		height: 20upx;
	}
	.newbutton {

		font-style: normal;
		height: 64rpx !important;
		line-height: 60rpx !important;
		z-index: 9990;
		width: 50rpx !important;
		box-sizing: border-box;
		margin-right: 10rpx;
		border: none !important;
		border-radius: 8rpx !important;
		font-size: 34rpx !important;
		position: absolute;
		right: 20rpx !important;
		color: #FFFFFF;
		text-align: center;
		top: 13px;
	}
	
	.newbuttonleft {
	
		font-style: normal;
		height: 64rpx !important;
		line-height: 60rpx !important;
		z-index: 9990;
		width: 450rpx !important;
		box-sizing: border-box;
		margin-right: 10rpx;
		border: none !important;
		border-radius: 8rpx !important;
		font-size: 34rpx !important;
		position: absolute;
		left: 20rpx !important;
		color: #515159;
		text-align: center;
		top: 13px;
		
	}

	.content {
		background-color: #edf1f4;
	}

	.box {
		width: 600rpx;
		border-bottom: 1px #CCCCCC solid;
		height: 80rpx;
		line-height: 80rpx;
		z-index: 9999;
	}

	.box .popupspan {
		width: 36.5%;
		display: inline-block;
		height: 80rpx;
		line-height: 80rpx;
		padding-left: 3.5%;
		color: #5a5a5a;
	}

	.box .popupinput {
		width: 52%;
		text-align: right;
		display: inline-block;
		height: 80rpx;
		line-height: 80rpx;
		padding-right: 30rpx;
		float: right;
	}

	.box .popupinput input {
		height: 100%;
		line-height: 100%;
		font-size: 30rpx;
	}

	.inputff {
		color: #BEBEBE;
		font-size: 30rpx;
	}

	.box .popupinput {
		font-size: 30rpx;
	}
</style>
